package com.study.mike.common.config;

import com.study.mike.model.entity.User;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * @author kh
 */
@Component
public class JwtConfig {
    // 定义一个签名的key
    private String signature = "kanghui";

    /**
     * 生成jwt
     *
     * @param user
     * @return
     */
    public String generateJWT(User user) {
        // 创建jwt对象
        JwtBuilder jwtBuilder = Jwts.builder();
        // 明确jwt的三分部分：heard + payload + signature
        String jwtToken = jwtBuilder
                //1.heard
                // 类型
                .setHeaderParam("typ", "jwt")
                // 加密算法
                .setHeaderParam("alg", "HS256")
                //2.负载 payload
                .claim("username", user.getName())
                .claim("age", user.getAge())
                // 主题
                .setSubject("learn")
                // 设置有效时间：获取当前系统时间再加上2小时
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 24))
                // 设置id 通过UUID生成
                .setId(UUID.randomUUID().toString())
                //3.signature
                .signWith(SignatureAlgorithm.HS256, signature)
                // 拼接 heard、payload、signature
                .compact();
        System.out.println(jwtToken);
        return jwtToken;
    }

    /**
     * 解析jwtToken
     */
    public void verificationJWT(String jwtToken) {
        // 创建解密对象
        JwtParser jwtParser = Jwts.parser();
        // 获取到的token
//        String jwtToken = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IktBTkdIVUkiLCJnZW5kZXIiOiJtYW4iLCJzdWIiOiJsZWFybiIsImV4cCI6MTY1NDUwMDQxOCwianRpIjoiOTEyOGU5NmItNTk5Yi00YzllLTg5OTctODI3ZjA5YWY1NTM5In0.LOcwlLP42S2MUgRMv0aaBDvZ79Lj5FXl--eSYfwoVLU";
        // 通过签名
        Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        System.out.println(claims.get("username"));
        System.out.println(claims.get("age"));
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
        // 有效期
        System.out.println(claims.getExpiration());

    }

    public void verify() {

    }
}
